import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useLocation, history, Link } from '@umijs/max';
import type { FormInstance } from 'antd';
import { message, Switch } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { updateCameraStatus, getCameras } from '@/services/api/camera';
import AddCamera from './components/add';

const handleEditUserStatus = async (is: boolean, fields: API.CameraResponseDto) => {
  const hide = message.loading('正在修改');
  try {
    const { status_code, message: msg } = await updateCameraStatus(
      { camera_id: fields.camera_id },
      {
        status: is ? 1 : 2,
      },
    );
    if (status_code === 200) {
      hide();
      message.success(msg);
      return true;
    }
    message.error(msg);
    return false;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

const CameraList: React.FC = () => {
  const location = useLocation();
  const routeUrl = location.pathname;
  const [searchParams, setSearchParams] = useState<{ [key: string]: any }>(location.state || {});

  const actionRef = useRef<ActionType>();
  const searchRef = useRef<FormInstance>();
  useEffect(() => {
    history.replace(routeUrl, { ...searchParams });
    searchRef.current?.setFieldsValue({ ...searchParams });
  }, [routeUrl, searchParams]);

  const columns: ProColumns<API.CameraResponseDto>[] = [
    {
      title: '查询',
      hideInTable: true,
      dataIndex: 'keyWords',
    },
    { title: 'ID', dataIndex: 'camera_id', search: false },
    { title: '标题', dataIndex: 'title', search: false },
    { title: '拉流URL', dataIndex: 'pull_url', ellipsis: true, search: false },
    { title: '推流URL', dataIndex: 'push_url', ellipsis: true, search: false },
    {
      title: '预测模型',
      dataIndex: 'model',
      align: 'center',
      valueEnum: {
        violent_detection: { text: '暴力检测' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 80,
      valueEnum: {
        1: { text: '启用' },
        2: { text: '禁用' },
      },
      render: (_, entity) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            checked={entity.status === 1}
            onChange={async (checked) => {
              const success = await handleEditUserStatus(checked, entity);
              if (success) actionRef.current?.reload();
            }}
          />
        );
      },
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      align: 'center',
      search: false,
      render: (val) =>
        typeof val === 'number' && val > 0 ? moment(val * 1000).format('YYYY/MM/DD HH:mm:ss') : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
      search: false,
      render: (val) =>
        typeof val === 'number' && val > 0 ? moment(val * 1000).format('YYYY/MM/DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 80,
      align: 'center',
      fixed: window.innerWidth < 596 ? false : 'right',
      render: (_, record) => [
        <div key="void" style={{ width: '8px' }} />,
        <Link
          key="edit"
          to={{ pathname: `/camera/details/${record.camera_id}` }}
          state={searchParams}
        >
          编辑
        </Link>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.CameraResponseDto>
        headerTitle={'用户列表'}
        rowKey="camera_id"
        scroll={{ x: 1300 }}
        actionRef={actionRef}
        formRef={searchRef}
        columns={columns}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          defaultCurrent: searchParams.current || 1,
          defaultPageSize: searchParams.pageSize || 10,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
        }}
        toolBarRender={() => [
          <AddCamera key="add_user" onSubmit={() => actionRef.current?.reload()} />,
        ]}
        request={async (params) => {
          const d = {
            ...params,
            page: params.current || 1,
            page_size: params.pageSize || 10,
            ...searchRef.current?.getFieldsValue(),
          };
          setSearchParams({ ...d });
          if ('current' in d) delete d.current;
          if ('pageSize' in d) delete d.pageSize;
          return getCameras({ ...d }).then(({ data }) => {
            return {
              data: data.items,
              success: true,
              total: data.total,
            };
          });
        }}
      />
    </PageContainer>
  );
};
export default CameraList;
